<?php 

class TransmissionProxy implements IProxy{
	public function doCall($req)
	{

	    
	    $request = json_encode($req);
	    $URI = "/transmission/rpc";
	    $Host = "localhost";
	    $Port = 9091;
	    $ReqHeader =
	        "POST $URI HTTP/1.1\n\r".
	        "Host: $Host\n\r".
	        "X-Transmission-Session-Id: ".$GLOBALS["X-Transmission-Session-Id"]."\n\r".
	        "Connection: Close\n\r".
	        "Content-Type: json\n\r".
	        "Accept: application/json, text/javascript, *.*\n\r".
	        "Content-Length: ".strlen($request)."\n\r\n\r".
	        "$request";
	    $socket = @fsockopen($Host, $Port, $errno, $errstr);
	    
	    if( !$socket ) return json_encode(array("errno" => $errno, "errstr" => $errstr, "result" => "error"));
	
	    $idx = 0;
	    $skip = 1;
	    $fullbody = $body = "";
	    fputs($socket, $ReqHeader);
	    while( !feof($socket) )
	    {
	        $responce[$idx] = fgets($socket, 128);
	        $fullbody .= $responce[$idx];

	       
	        if( $skip == 1 && ereg("^{", $responce[$idx]) ) $skip = 0;
	        if( !$skip ) $body .= $responce[$idx];
	        $idx++;
	    }
	    fclose($socket);
	
	    //#####################################################################
	    //check for 409
	    //#####################################################################
	
	    if( preg_match("/http\/\d\.\d\s+409\s+conflict/si", $fullbody) )
	    {
	        if( preg_match("/x\-transmission\-session\-id\:\s+([a-z0-9]{48})/si", $fullbody, $matches) )
	        {
	            
	            $GLOBALS["X-Transmission-Session-Id"] = $matches[1];
	            return $this->doCall($req);
	        }
	    }
	    
	    //#####################################################################
	    //#####################################################################
	    
	    return $body;
	
	
	}


} 

?>


